package com.edu.fafu.studentrepair;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.YuvImage;
import android.location.Location;
import android.net.IpSecManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.edu.fafu.studentrepair.command.Dictionary;
import com.edu.fafu.studentrepair.command.LocalDataStream;
import com.edu.fafu.studentrepair.command.ReJsonRsp;

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {
    private EditText iden;
    private EditText pwd;
    private Button btn;
    private ProgressDialog pd;
    private String pdTitle;
    private String pdMsg;
    private int showToast = 1;
    private String msg = "";
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == showToast) {
                showToast();
            } }
    };
    private  void showPD(){
        pd= ProgressDialog.show(this, pdTitle, pdMsg);
    }
    private  void showPD(String pdTitle,String pdMsg){
        pd= ProgressDialog.show(this, pdTitle, pdMsg);
    }
    private void dismissPD(){
        pd.dismiss();
    }
    private void showToast(){
        Toast toast = Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_LONG);
        toast.show();
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.login);
        iden = findViewById(R.id.login_iden);
        pwd  = findViewById(R.id.login_pwd);
        btn = findViewById(R.id.login_btn);
        /**
         * 读取本地，查看时候有登陆记录，有则直接跳
         */
        try {
            String data = LocalDataStream.read(openFileInput("data"));
            if(data != null && !data.equals("")){
                /**
                 * 有信息，获得信息，登录....
                 */
                Log.i("xaxas", "onCreate: "+data);
                String idenstr = data.split("_")[1];
                String pwdstr = data.split("_")[2];
                iden.setText(idenstr);
                pwd.setText(pwdstr);
                showPD("登录","登录请求中");
                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        if(login()){
                            Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity(intent);
                            LoginActivity.this.finish();
                        }
                        pd.dismiss();
                    }
                };
                Thread thread = new Thread(runnable);
                thread.start();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        super.onCreate(savedInstanceState);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPD("登录","登录请求中");
                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        if(login()){
                            Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity(intent);
                            LoginActivity.this.finish();
                        }
                        pd.dismiss();
                    }
                };
                Thread thread = new Thread(runnable);
                thread.start();
            }

        });
    }
    private Boolean login() { //将用户信息持久化
        try {
            FileOutputStream out = openFileOutput("data", Context.MODE_PRIVATE);
            String idenstr = iden.getText().toString();
            String pwdstr = pwd.getText().toString();
            OkHttpClient okHttpClient = new OkHttpClient();
            Log.i("login", "login: "+Dictionary.url.head + "app/stulogin?studentId=" + idenstr + "&password=" + pwdstr);
            final Request request = new Request.Builder()
                    .url(Dictionary.url.head + "app/stulogin?studentId=" + idenstr + "&password=" + pwdstr)
                    .get()
                    .build();
            Response response = null;
            try {
                response = okHttpClient.newCall(request).execute();
                String json = response.body().string();
                Log.i("login", "login: "+json);
                ReJsonRsp reJsonRsp = JSONObject.parseObject(json,new TypeReference<ReJsonRsp>(){});
                Integer code = reJsonRsp.getCode();
                if (code.equals(0)) {
                    JSONObject jsonObject = (JSONObject) reJsonRsp.getData();
                    Integer studentId = (Integer) jsonObject.get("id");
                    String name = (String) jsonObject.get("name");
                    Integer isused = (Integer) jsonObject.get("isused");
                    String imgurl = (String) jsonObject.get("imgurl");
                    Integer area = (Integer) jsonObject.get("area");
                    String str = studentId + "_" + idenstr + "_" + pwdstr+"_"+isused+"_"+imgurl+"_"+name+"_"+area;
                    LocalDataStream.writer(str, out);
                    return true;
                }
                msg = reJsonRsp.getMsg();
                Message message = new Message();
                message.what=showToast;
                handler.sendMessage(message);
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return  false;
        }
    }
}
